import React, { useState, useEffect, useCallback } from 'react';
import {
  Plus,
  CheckCircle,
  XCircle,
  RefreshCw,
  Trash2,
  Star,
  Clock,
  Settings,
  Zap,
} from 'lucide-react';
import { aiProviderApi } from '../api';
import type { AIProvider, CreateAIProviderRequest, AIProviderType } from '../api/types';
import { useApiError } from '../hooks/useApiError';
import { useConfirm } from '../hooks/useConfirm';
import { toast } from '../stores/toastStore';

const AIProviders: React.FC = () => {
  const { handleError } = useApiError();
  const { confirmDelete, setLoading: setConfirmLoading, ConfirmComponent } = useConfirm();
  const [providers, setProviders] = useState<AIProvider[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddForm, setShowAddForm] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState<number | null>(null);

  // 添加提供商表单状态
  const [newProvider, setNewProvider] = useState<CreateAIProviderRequest>({
    name: '',
    provider_type: 'openai',
    api_key: '',
    api_secret: '',
    base_url: '',
    config: {},
  });

  const loadProviders = useCallback(async () => {
    try {
      setLoading(true);
      const data = await aiProviderApi.list();
      const providersList = data?.rows || [];
      setProviders(providersList);
    } catch (error) {
      handleError(error, '加载AI服务提供商列表失败');
    } finally {
      setLoading(false);
    }
  }, [handleError]);

  useEffect(() => {
    loadProviders();
  }, [loadProviders]);

  const handleAddProvider = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await aiProviderApi.create(newProvider);
      setNewProvider({
        name: '',
        provider_type: 'openai',
        api_key: '',
        api_secret: '',
        base_url: '',
        config: {},
      });
      setShowAddForm(false);
      toast.success('AI服务提供商添加成功');
      loadProviders();
    } catch (error) {
      handleError(error, '添加AI服务提供商失败');
    }
  };

  const handleActivate = async (id: number) => {
    try {
      await aiProviderApi.activate(id);
      toast.success('AI服务提供商激活成功');
      loadProviders();
    } catch (error) {
      handleError(error, '激活AI服务提供商失败');
    }
  };

  const handleRefresh = async (id: number) => {
    try {
      setIsRefreshing(id);
      await aiProviderApi.refresh(id);
      toast.success('AI服务提供商信息刷新成功');
      loadProviders();
    } catch (error) {
      handleError(error, '刷新AI服务提供商信息失败');
    } finally {
      setIsRefreshing(null);
    }
  };

  const handleDelete = async (id: number, name: string) => {
    if (
      await confirmDelete('删除AI服务提供商', `确定要删除提供商"${name}"吗？删除后将无法恢复。`)
    ) {
      try {
        setConfirmLoading(true);
        await aiProviderApi.delete(id);
        toast.success('AI服务提供商删除成功');
        loadProviders();
      } catch (error) {
        handleError(error, '删除AI服务提供商失败');
      } finally {
        setConfirmLoading(false);
      }
    }
  };

  const getProviderIcon = (type: AIProviderType) => {
    switch (type) {
      case 'openai':
        return '🤖';
      case 'deepseek':
        return '🧠';
      case 'heygen':
        return '🎥';
      default:
        return '🔧';
    }
  };

  const getProviderName = (type: AIProviderType) => {
    switch (type) {
      case 'openai':
        return 'OpenAI';
      case 'deepseek':
        return 'DeepSeek';
      case 'heygen':
        return 'HeyGen';
      default:
        return type;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'text-green-500 bg-green-50';
      case 'error':
        return 'text-red-500 bg-red-50';
      case 'pending':
        return 'text-yellow-500 bg-yellow-50';
      case 'disabled':
        return 'text-gray-500 bg-gray-50';
      default:
        return 'text-gray-500 bg-gray-50';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'active':
        return '正常';
      case 'error':
        return '错误';
      case 'pending':
        return '待验证';
      case 'disabled':
        return '已禁用';
      default:
        return status;
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-black text-white p-6">
        <div className="flex items-center justify-center h-64">
          <RefreshCw className="animate-spin w-8 h-8 text-blue-500" />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-black text-white p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-100 mb-2">AI服务提供商</h1>
            <p className="text-gray-400">管理OpenAI、DeepSeek等AI服务提供商账户</p>
          </div>
          <button
            onClick={() => setShowAddForm(true)}
            className="flex items-center px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all"
          >
            <Plus className="w-5 h-5 mr-2" />
            添加提供商
          </button>
        </div>

        {/* Add Provider Form */}
        {showAddForm && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-gray-900 border border-gray-800 rounded-xl p-6 w-full max-w-md max-h-[90vh] overflow-y-auto">
              <h2 className="text-xl font-semibold text-gray-100 mb-4">添加AI服务提供商</h2>
              <form onSubmit={handleAddProvider} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">提供商类型</label>
                  <select
                    value={newProvider.provider_type}
                    onChange={e =>
                      setNewProvider({
                        ...newProvider,
                        provider_type: e.target.value as AIProviderType,
                      })
                    }
                    className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    required
                  >
                    <option value="openai">OpenAI</option>
                    <option value="deepseek">DeepSeek</option>
                    <option value="heygen">HeyGen</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">名称</label>
                  <input
                    type="text"
                    value={newProvider.name}
                    onChange={e => setNewProvider({ ...newProvider, name: e.target.value })}
                    placeholder="例如: 主要OpenAI账户"
                    className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">API密钥</label>
                  <input
                    type="password"
                    value={newProvider.api_key}
                    onChange={e => setNewProvider({ ...newProvider, api_key: e.target.value })}
                    placeholder="输入API密钥"
                    className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    required
                  />
                </div>

                {newProvider.provider_type === 'openai' && (
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">
                      自定义API地址 (可选)
                    </label>
                    <input
                      type="url"
                      value={newProvider.base_url || ''}
                      onChange={e => setNewProvider({ ...newProvider, base_url: e.target.value })}
                      placeholder="https://api.openai.com/v1"
                      className="w-full px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                  </div>
                )}

                <div className="flex justify-end space-x-3 pt-4">
                  <button
                    type="button"
                    onClick={() => setShowAddForm(false)}
                    className="px-4 py-2 text-gray-400 hover:text-gray-300 transition-colors"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    添加
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* Providers List */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {providers.map(provider => (
            <div
              key={provider.id}
              className={`bg-gray-900 border rounded-xl p-6 hover:border-gray-700 transition-colors ${
                provider.is_active ? 'border-green-500' : 'border-gray-800'
              }`}
            >
              {/* Provider Header */}
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center space-x-3">
                  <span className="text-2xl">{getProviderIcon(provider.provider_type)}</span>
                  <div>
                    <h3 className="text-lg font-semibold text-gray-100">{provider.name}</h3>
                    <p className="text-sm text-gray-400">
                      {getProviderName(provider.provider_type)}
                    </p>
                  </div>
                </div>
                {provider.is_active && <Star className="w-5 h-5 text-yellow-500 fill-current" />}
              </div>

              {/* Status */}
              <div className="mb-4">
                <div className="flex items-center space-x-2 mb-2">
                  <span
                    className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(provider.status)}`}
                  >
                    {getStatusText(provider.status)}
                  </span>
                  {provider.status === 'active' ? (
                    <CheckCircle className="w-4 h-4 text-green-500" />
                  ) : provider.status === 'error' ? (
                    <XCircle className="w-4 h-4 text-red-500" />
                  ) : (
                    <Clock className="w-4 h-4 text-yellow-500" />
                  )}
                </div>
                {provider.status_msg && (
                  <p className="text-xs text-gray-500">{provider.status_msg}</p>
                )}
              </div>

              {/* Provider Info */}
              <div className="space-y-2 mb-4">
                {provider.display_name && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">显示名称:</span>
                    <span className="text-gray-300">{provider.display_name}</span>
                  </div>
                )}
                {provider.email && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">邮箱:</span>
                    <span className="text-gray-300">{provider.email}</span>
                  </div>
                )}
                {provider.capabilities && provider.capabilities.length > 0 && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">能力:</span>
                    <span className="text-gray-300">
                      {provider.capabilities.slice(0, 2).join(', ')}
                    </span>
                  </div>
                )}
                {provider.last_check_at && (
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-400">最后检查:</span>
                    <span className="text-gray-300">{provider.last_check_at}</span>
                  </div>
                )}
              </div>

              {/* Usage Info */}
              {provider.usage && (
                <div className="bg-gray-800 rounded-lg p-3 mb-4">
                  <h4 className="text-sm font-medium text-gray-300 mb-2">使用统计</h4>
                  <div className="space-y-1">
                    {Object.entries(provider.usage)
                      .slice(0, 3)
                      .map(([key, value]) => (
                        <div key={key} className="flex justify-between text-xs">
                          <span className="text-gray-400">{key}:</span>
                          <span className="text-gray-300">{String(value)}</span>
                        </div>
                      ))}
                  </div>
                </div>
              )}

              {/* Actions */}
              <div className="flex justify-between items-center">
                <div className="flex space-x-2">
                  {!provider.is_active && provider.status === 'active' && (
                    <button
                      onClick={() => handleActivate(provider.id)}
                      className="flex items-center px-3 py-1.5 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700 transition-colors"
                    >
                      <Zap className="w-4 h-4 mr-1" />
                      激活
                    </button>
                  )}
                  <button
                    onClick={() => handleRefresh(provider.id)}
                    disabled={isRefreshing === provider.id}
                    className="flex items-center px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
                  >
                    <RefreshCw
                      className={`w-4 h-4 mr-1 ${isRefreshing === provider.id ? 'animate-spin' : ''}`}
                    />
                    刷新
                  </button>
                </div>
                <div className="flex space-x-2">
                  <button
                    onClick={() => handleDelete(provider.id, provider.name)}
                    disabled={provider.is_active}
                    className="p-2 text-red-500 hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    title={provider.is_active ? '无法删除活跃的提供商' : '删除提供商'}
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {providers.length === 0 && (
          <div className="text-center py-12">
            <div className="w-16 h-16 bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-4">
              <Settings className="w-8 h-8 text-gray-600" />
            </div>
            <h3 className="text-lg font-medium text-gray-400 mb-2">暂无AI服务提供商</h3>
            <p className="text-gray-500 mb-4">添加OpenAI、DeepSeek等AI服务提供商以开始使用。</p>
            <button
              onClick={() => setShowAddForm(true)}
              className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              <Plus className="w-4 h-4 mr-2" />
              添加第一个提供商
            </button>
          </div>
        )}

        <ConfirmComponent />
      </div>
    </div>
  );
};

export default AIProviders;
